package breadbox.pastry;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Conf {
	// size of the leaf set
	private static int L = 16;

	// exponent of the base
	private static int B = 4;

	// size of the neighborhood set
	private static int M = 32;

	private static int BOOTSTRAP_PORT = 33401;
	
	private static InetAddress BOOTSTRAP_IP;
	
	private static boolean IS_BOOTSTRAP_NODE = true;
	
	private static int MY_PORT = 33401;
	
	private static long PULSE = 2700000L; //45 minutes
	
	private static long SAVEPULSE = 300000L; //5 minutes

	public static int l() {
		return L;
	}

	public static int b() {
		return B;
	}

	public static int m() {
		return M;
	}
	
	public static long pulse() {
		return PULSE;
	}
	
	public static long savePulse() {
		return SAVEPULSE;
	}

	public static int bootstrapPort() {
		return BOOTSTRAP_PORT;
	}
	
	public static InetAddress bootstrapIP() {
		return BOOTSTRAP_IP;
	}
	
	public static boolean isBootstrapNode() {
		return IS_BOOTSTRAP_NODE;
	}
	
	public static int myPort() {
		return MY_PORT;
	}
	
	public static void readConf(String filename) {
		try {
			BOOTSTRAP_IP = InetAddress.getLocalHost();
			Scanner conf = new Scanner(new File(filename));
			while (conf.hasNextLine()) {
				String line = conf.nextLine();
				String[] parts = line.split(":");
				if (parts[0] == "" || parts[1] == "" || parts[0].trim().charAt(0) == '#') {
					continue;
				} else {
					try {
					if (parts[0].trim().equalsIgnoreCase("pastry.l")) {
						L = Integer.parseInt(parts[1].trim());
					} else if (parts[0].trim().equalsIgnoreCase("pastry.m")) {
						M = Integer.parseInt(parts[1].trim());
					} else if (parts[0].trim().equalsIgnoreCase("pastry.b")) {
						B = Integer.parseInt(parts[1].trim());
					} else if (parts[0].trim().equalsIgnoreCase("pastry.bootstrap_port")) {
						BOOTSTRAP_PORT = Integer.parseInt(parts[1].trim());
					} else if (parts[0].trim().equalsIgnoreCase("pastry.bootstrap_ip")) {
						BOOTSTRAP_IP = Inet4Address.getByName(parts[1].trim());
					} else if (parts[0].trim().equalsIgnoreCase("pastry.is_bootstrap_node")) {
						IS_BOOTSTRAP_NODE = Boolean.parseBoolean(parts[1].trim());
					} else if (parts[0].trim().equalsIgnoreCase("pastry.my_port")) {
						MY_PORT = Integer.parseInt(parts[1].trim());
					} else {
						continue;
					}
					} catch (NumberFormatException nex) {
						//ignore
					}
				}
			}
		} catch (FileNotFoundException fex) {
			// ignore
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
